//
//  LoginViewController.m
//  Products_B
//
//  Created by lanou on 16/6/7.
//  Copyright © 2016年 朋学友. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ProtocolTableViewController.h"
#import "FindPassWordViewController.h"
#import "DataSecurity.h"

#define kLoginURL @"http://api.izhangchu.com/?appVersion=4.4&sysVersion=9.3.2&devModel=iPhone"

@interface LoginViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIView         *bigView;
@property (weak, nonatomic) IBOutlet UITextField    *numPhoneTf;
@property (weak, nonatomic) IBOutlet UITextField    *passwordTf;
@property (weak, nonatomic) IBOutlet UIButton       *forgetPassWordButton;
@property (weak, nonatomic) IBOutlet UIButton       *sureButton;
@property (weak, nonatomic) IBOutlet UIButton       *gouButton;
@property (weak, nonatomic) IBOutlet UILabel        *protocolLabel;
@property (weak, nonatomic) IBOutlet UIButton       *wechatButton;
@property (weak, nonatomic) IBOutlet UIButton       *qqButton;
@property (weak, nonatomic) IBOutlet UIButton       *taobaoButton;
@property (weak, nonatomic) IBOutlet UIButton       *weiboButton;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"登录";
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemAction:)];
    rightBarButtonItem.tintColor = [UIColor orangeColor];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;
    
    // 给label上的文字添加下划线
    NSMutableAttributedString *content = [[NSMutableAttributedString alloc]initWithString:_protocolLabel.text];
    // 确定需要加下划线的文字范围
    NSRange contentRange = {0,[content length]};
    // 根据范围给文字设置下划线
    [content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
    
    // 根据范围给文字颜色
     [content addAttributes:[NSDictionary dictionaryWithObject:[UIColor orangeColor] forKey:NSForegroundColorAttributeName] range:contentRange];
    
    _protocolLabel.attributedText = content;
    _protocolLabel.userInteractionEnabled = YES;
    // 添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_protocolLabel addGestureRecognizer:tap];

    [self.view addSubview:_protocolLabel];
}

// 登录确定按钮
- (IBAction)sureButtonAction:(UIButton *)sender {
    // NSDictionary *parDic= @{@"device_id":@"0119b42dec7",@"device_name":@"Simulator",@"device_type":@9.300000,@"methodName":@"UserSignin",@"mobile":_numPhoneTf.text,@"password":_passwordTf.text,@"token":@"",@"user_id":@"",@"version":@4.4};
    if (_numPhoneTf.text.length == 0) {
        [self showAlertWithTitle:@"手机号码不能为空"];
        return;
    }
    if (_numPhoneTf.text.length < 13) { // 13 == 11个手机号码 + 2个“-”
        [self showAlertWithTitle:@"请输入正确的手机号码"];
        return;
    }
    if (_passwordTf.text.length == 0) {
        [self showAlertWithTitle:@"密码不能为空"];
        return;
    }
    // 手机号码当中含“-”，下面对手机号码按“-”进行分割
    NSArray *array = [_numPhoneTf.text componentsSeparatedByString:@"-"];
    // 重新拼接字符串,拼接后的字符串作为手机号码参数传入服务器
    NSString *numPhoneString = [NSString stringWithFormat:@"%@%@%@",array[0],array[1],array[2]];
    // 对密码用MD5进行加密传入服务器，只有加密后服务器才能识别
    NSString *md5String = [[DataSecurity shareInstance] MD5WithString:_passwordTf.text];
    // 将手机号码和密码作为参数上传到服务器
    NSDictionary *parDic= @{@"device_id":@"0119b42dec7",@"device_name":@"Simulator",@"device_type":@9.300000,@"methodName":@"UserSignin",@"mobile":numPhoneString,@"password":md5String,@"token":@"",@"user_id":@"",@"version":@4.4};
    [RequestManager requestWithUrl:kLoginURL requestType:RequestTypePOST parDic:parDic finish:^(NSData *data) {
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"++++ %@",json);
        // 将网络请求返回的字典中两个值唯一存储到本地，以后根据唯一值判断是否登录
        [[NSUserDefaults standardUserDefaults] setObject:json[@"data"][@"token"]forKey:@"token"];
        [[NSUserDefaults standardUserDefaults] setObject:json[@"data"][@"user_id"]forKey:@"user_id"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
//        UIViewController *lastVc = self.navigationController.viewControllers[1];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } error:^(NSError *error) {
        NSLog(@"请求数据失败");
    }];
}



- (void)tapAction:(UITapGestureRecognizer *)tap {
    // 跳转到服务协议和条款界面
    ProtocolTableViewController *protocolVc = [[ProtocolTableViewController alloc] init];
    [self.navigationController pushViewController:protocolVc animated:YES];
}

// 跳转到注册界面
- (void)rightBarButtonItemAction:(UIBarButtonItem *)barButton {
    RegisterViewController *registerVc = [[RegisterViewController alloc] init];
    [self.navigationController pushViewController:registerVc animated:YES];
}


- (IBAction)forgetPasswordButtonAction:(UIButton *)sender {
    FindPassWordViewController *findVc = [[FindPassWordViewController alloc] init];
    [self.navigationController pushViewController:findVc animated:YES];
}


- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [_numPhoneTf resignFirstResponder];
    [_passwordTf resignFirstResponder];
}

- (void)showAlertWithTitle:(NSString *)title {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *userAction = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:userAction];
    [self presentViewController:alert animated:YES completion:nil];
    [self performSelector:@selector(dissmissAlert:) withObject:alert afterDelay:1.5];
}

- (void)dissmissAlert:(UIAlertController *)alert {
    [alert dismissViewControllerAnimated:YES completion:nil];
}

// textField触发方法
- (IBAction)textFieldDidChange:(UITextField *)sender {
  
}

// 限制输入框的格式和字符长度(该方法每当输入一个字符时就调用，输入一次，调用一次)
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    // string指的是正在输入的当前字符串
    BOOL isChange = YES;
    
    if (textField == self.numPhoneTf) {
        //字符串删除时触发
        if ([string isEqualToString:@""] && range.length > 0) {
            isChange = YES;
            //字符串写入时触发
        } else {
            if (textField.text.length >= 13) {
                isChange = NO;
            } else {
                // 将不可变字符串转成可变字符串
                NSMutableString *newText = [NSMutableString stringWithString:string];
                NSMutableString *mutString = [[NSMutableString alloc] init];
                if (textField.text.length <= 13) {
                    if (textField.text.length < 4) {
                        if ((textField.text.length + 1) % 4 == 0) {
                            [mutString appendString:@"-"];
                        }
                    } else {
                        if (((textField.text.length - 4) + 1) % 5 == 0) {
                            [mutString appendString:@"-"];
                        }
                    }
                }
                [mutString appendString:newText];
                string = [mutString uppercaseString] ;
                textField.text = [NSString stringWithFormat:@"%@%@",textField.text,string];
            }
            isChange = NO;
        }
    }
    return isChange;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
